package com.example.my.shop.mybatis.controller;

import com.example.my.shop.mybatis.TbUser;
import com.example.my.shop.mybatis.service.Imp.TbUserServiceImpl;
import com.example.my.shop.mybatis.service.TbUserService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/displayUserById")
public class DisplayUser extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决json中文乱码
        resp.setContentType("text/json,charset=utf-8");

        TbUserService tbUserService = new TbUserServiceImpl();
        int id = Integer.parseInt(req.getParameter("id"));
        TbUser user = tbUserService.selectUserById(id);
        //因为前台是用ajax的json格式来进行数据传输的，所以需要把查询出来的结果也转换为json的格式返回给前台
//        import com.fasterxml.jackson.databind.ObjectMapper;
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);

        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }
}
